package com.tywj.buscustomerapp.view.fragment;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.CityBean;
import com.tywj.buscustomerapp.model.bean.TravelLineBean;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.utils.myadapter.CommonRcvAdapter;
import com.tywj.buscustomerapp.utils.myadapter.item.AdapterItem;
import com.tywj.buscustomerapp.view.activity.ChooseLocationActivity;
import com.tywj.buscustomerapp.view.activity.SearchActivity;
import com.tywj.buscustomerapp.view.item.TravleLineItem;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class TrainTravelFragment extends BaseFragment {
    private static TrainTravelFragment fragment = new TrainTravelFragment();
    private ImageView exchange;
    private TextView startText;
    private TextView endText;
    private String end;
    private String start;
    private ImageView search;
    private List<TravelLineBean> lines = new ArrayList<>();
    private CommonRcvAdapter<TravelLineBean> adapter;
    private RecyclerView recyclerView;
    private RelativeLayout error;
    private TextView error_btn;
    private RelativeLayout error_null;
    private TextView error_null_btn;
    private SmartRefreshLayout srl;

    public static TrainTravelFragment getInstance() {
        return fragment;
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_travel;
    }


    @Override
    protected void lazyLoad() {
        exchange = findViewById(R.id.travel_exchange);
        startText = findViewById(R.id.start_text);
        endText = findViewById(R.id.end_text);
        search = findViewById(R.id.travel_search);
        recyclerView = findViewById(R.id.travel_recycler);
        srl = findViewById(R.id.class_refresh);
        error = findViewById(R.id.error);
        error_btn = findViewById(R.id.error_btn);
        error_null = findViewById(R.id.error_null);
        error_null_btn = findViewById(R.id.error_null_btn);
        start = SPUtils.getStartAndEnd(getActivity().getApplicationContext())[0];
        end = SPUtils.getStartAndEnd(getActivity().getApplicationContext())[1];
        if (start==null || start.equals("") || start.equals("上车地点")) {
            start = "上车地点";
            startText.setText("上车地点");
        }else
            startText.setText(start);
        if (end==null || end.equals("") || end.equals("下车地点")) {
            end = "下车地点";
            endText.setText("下车地点");
        }else
            endText.setText(end);
        adapter  = new CommonRcvAdapter<TravelLineBean>(lines) {
            @NonNull
            @Override
            public AdapterItem createItem(Object type) {
                return new TravleLineItem();
            }
        };
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        srl.autoRefresh();

    }


    public void loadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    CityBean cityBean = SPUtils.getCity(getActivity().getApplicationContext());
                    if (cityBean !=null && cityBean.getCityId()!=null && !cityBean.getCityId().equals("") ){
                        String msg = WebServicrUtils.getInstance().getTravelLine4(cityBean.getCityId(),"火车站");
                        InputStream in_nocode = new ByteArrayInputStream(msg.getBytes("UTF-8"));
                        List<TravelLineBean> list = WebServicrUtils.getInstance().getLines(in_nocode);
                        Message message = new Message();
                        message.what = 1;
                        message.obj = list;
                        handler.sendMessage(message);
                    }else{
                        String msg = WebServicrUtils.getInstance().getTravelLine4("001","火车站");
                        InputStream in_nocode = new ByteArrayInputStream(msg.getBytes("UTF-8"));
                        List<TravelLineBean> list = WebServicrUtils.getInstance().getLines(in_nocode);
                        Message message = new Message();
                        message.what = 1;
                        message.obj = list;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                error.setVisibility(View.GONE);
                error_null.setVisibility(View.GONE);
                lines = (List<TravelLineBean>) msg.obj;
                if (lines!=null && lines.size()>0){
                    adapter.setData(lines);
                    adapter.notifyDataSetChanged();
                    if (srl.isRefreshing()){
                        srl.finishRefresh();
                    }
                }else{
                    adapter.setData(lines);
                    adapter.notifyDataSetChanged();
                    srl.finishRefresh();
                    error_null.setVisibility(View.VISIBLE);
                }
            }else if (msg.what==0){
                error.setVisibility(View.VISIBLE);
                srl.finishRefresh();
            }
        }
    };

    @Override
    protected void ititClick() {
        exchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里判断的有点多
                if (start!=null && !start.equals("上车地点") && !start.equals("") && !start.equals("下车地点")
                        && end!=null && !end.equals("上车地点") && !end.equals("下车地点") && !end.equals("")) {
                    exchangeText();
                    String[] cash = SPUtils.getStartAndEnd(getContext().getApplicationContext());
                    double[] cashL = SPUtils.getStartAndEndLatLng(getContext().getApplicationContext());
                    SPUtils.rememberStart(getContext().getApplicationContext(),cash[1],cashL[2]+"",cashL[3]+"");
                    SPUtils.rememberEnd(getContext().getApplicationContext(),cash[0],cashL[0]+"",cashL[1]+"");
                }
            }
        });
        startText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChooseLocationActivity.class);
                intent.putExtra("type",0);
                startActivityForResult(intent,0);
            }
        });

        endText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChooseLocationActivity.class);
                intent.putExtra("type",1);
                startActivityForResult(intent,1);
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SearchActivity.class);
                intent.putExtra("start&end",SPUtils.getStartAndEndLatLng(getContext().getApplicationContext()));
                startActivity(intent);
//                startActivity(new Intent(getContext(), MapTicketActivity.class));

            }
        });
        srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                lines.clear();
                loadData();
            }
        });
        error_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                srl.autoRefresh();
                error.setVisibility(View.GONE);
            }
        });
        error_null_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                srl.autoRefresh();
                error_null.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==1001) {
            PoiItem poi = data.getParcelableExtra("poi");
            switch (requestCode){
                case 0:
                    if (poi!=null){
                        start = poi.getTitle();
                        startText.setText(start);
                        SPUtils.rememberStart(getActivity().getApplicationContext(),start,poi.getLatLonPoint().getLatitude()+"",
                                poi.getLatLonPoint().getLongitude()+"");
                    }
                    break;
                case 1:
                    if (poi!=null){
                        end = poi.getTitle();
                        endText.setText(end);
                        SPUtils.rememberEnd(getActivity().getApplicationContext(),end,poi.getLatLonPoint().getLatitude()+"",
                                poi.getLatLonPoint().getLongitude()+"");
                    }
                    break;
            }
        }else if (resultCode==1002){
//            loadData();
            srl.autoRefresh();
        }

    }



    private void exchangeText(){
        int[] position = new int[2];
        startText.getLocationOnScreen(position);
        int[] position1 = new int[2];
        endText.getLocationOnScreen(position1);
        Animation translateAnimation=new TranslateAnimation(0,0,0,position1[1]-position[1]);
        translateAnimation.setDuration(500);
        startText.startAnimation(translateAnimation);
        Animation translateAnimation1=new TranslateAnimation(0,0,0,position[1]-position1[1]);
        translateAnimation1.setDuration(500);
        endText.startAnimation(translateAnimation1);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                startText.clearAnimation();
                endText.clearAnimation();
                String cash = end;
                end = start;
                start = cash;
                startText.setText(start);
                endText.setText(end);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler!=null)
            handler.removeMessages(1);
    }
    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("主页-火车");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("主页-火车");
    }
}
